package live.ciallo.discipline.task;

import live.ciallo.discipline.pojo.TaskInfo;
import live.ciallo.discipline.service.NeowSendMessageImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.config.Task;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.*;

/**
 * 定时任务调度
 */
@Slf4j
@Component
@AllArgsConstructor
public class TaskScheduler {
    private final NeowSendMessageImpl neowSendMessage;
    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
    private final ConcurrentHashMap<String, ScheduledFuture<?>> taskFutures = new ConcurrentHashMap<>();
    
    // 提交新任务列表（会取消旧任务）
    public synchronized void submitTasks(List<TaskInfo> taskInfos) {
        // 1. 取消所有旧任务
        taskFutures.values().forEach(future -> future.cancel(true));
        taskFutures.clear();

        // 2. 调度新任务
        taskInfos.forEach(task -> {
            String taskKey = task.getUserId() + "|" + task.getContent();
            ScheduledFuture<?> future = executor.scheduleAtFixedRate(
                () -> runTask(task),
                initialDelay(task.getTime()),
                24 * 60 * 60 * 1000L,  // 24小时周期
                TimeUnit.MILLISECONDS
            );
            taskFutures.put(taskKey, future);
        });
    }

    // 计算首次执行延迟
    private long initialDelay(LocalTime targetTime) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime nextRun = now.with(targetTime);
        if (now.isAfter(nextRun)) {
            nextRun = nextRun.plusDays(1);  // 如果今天时间已过，改为明天
        }
        return Duration.between(now, nextRun).toMillis();
    }

    // 任务执行逻辑
    private void runTask(TaskInfo task) {
        log.info("[{}]执行任务 id: {}, title: {}, content: {}",
                LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME),
                task.getUserId(), task.getTitle(), task.getContent());
        neowSendMessage.sendMessage(task.getUserId(), task.getTitle(), task.getContent());
    }

    // 关闭调度器
    public void shutdown() {
        executor.shutdown();
    }
}